package com.myjwt.jwtutils;

import com.alibaba.druid.support.spring.stat.annotation.Stat;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.Verification;
import sun.reflect.generics.tree.VoidDescriptor;

import javax.swing.*;
import java.io.PrintWriter;
import java.time.temporal.ValueRange;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

/**
 * @author admin
 * @version 1.0 <br/>
 * <p style="font-family:SimSun;font-weight:bold">时间:<br/>2021/12/2 22:16</p>
 * @description
 */
public class JwtUtils {
    //获取随机盐
    private static final   String salt=GetSalt.getSalt();

    /**
     * 生成token令牌
     * @param map 需要分装的payload:用户名，年龄等个人信息，不能包含敏感信息
     * @return 返回值是token
     */
    public static String getToken(Map<String,String> map){
        //不写头信息，默认是typ:JWT
        Calendar instance=Calendar.getInstance();
        instance.add(Calendar.DATE, 7);
        JWTCreator.Builder builder = JWT.create();
        //payload
        map.forEach((k,v)->{
            builder.withClaim(k,v);
                });

        String token = builder
                //设置过期时间
                .withExpiresAt(instance.getTime())
                //签名
                .sign(Algorithm.HMAC256(salt));

        return token;
    }

    /**
     * 验证token的合法性
     * @param token 令牌
     */
    public static boolean verify(String token){
        try {
            JWT.require(Algorithm.HMAC256(salt)).build().verify(token);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}
